//
//  RankBottomSliderView.swift
//  MM2
//
//  Created by 李成明 on 2022/1/8.
//

import UIKit

private enum State {
    case addPhtot
    case pk
}

private class PkView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addsubViews([imageView, pkBtn, faceValueLabel])
        imageView.snp.makeConstraints { make in
            make.left.equalTo(self).offset(20)
            make.centerY.equalTo(self).offset(-kSafeAreaBottomH)
            make.size.equalTo(CGSize(width: 150, height: 150))
        }
        faceValueLabel.snp.makeConstraints { make in
            make.left.equalTo(imageView.snp.right).offset(20)
            make.top.bottom.right.equalTo(self).offset(-kSafeAreaBottomH)
        }
        
        pkBtn.frame = CGRect(x: 40, y: 250 - kSafeAreaBottomH, width: kScreenWidth - 80, height: 50)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var data: RankListModel? {
        didSet {
            updateUI()
        }
    }
    
    private var pkClosure: ((RankListModel) -> Void)?
    
    private lazy var pkBtn: UIButton = {
        let view = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 25
        view.layer.borderColor = orgMainColor.cgColor
        view.layer.borderWidth = 1
        
        view.backgroundColor = orgMainColor
        view.setTitleColor(.white, for: .normal)
        view.setTitle("发起挑战", for: .normal)
        view.addTarget(self, action: #selector(btnClickAction), for: .touchUpInside)
        return view
    }()
    
    private var faceValueLabel: UILabel = {
        let view = UILabel()
        view.textAlignment = .center
        view.textColor = faceValueColor
        return view
    }()
    
    private var imageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    private func updateUI() {
        guard let data = data else { return }

        imageView.setImageWithUrlStr(data.imgUrl)
        
        let attrStr = NSMutableAttributedString.init(string: String(format: "%.2f", data.faceValue),attributes: [.font: UIFont.systemFont(ofSize: 16)])
        attrStr.addAttributes([.font: UIFont(name: "Verdana-Italic", size: 70)!], range: NSRange(location: 0, length: data.faceValue > 10 ? 2 : 1))
        faceValueLabel.attributedText = attrStr
    }
    
    @objc private func btnClickAction() {
        guard let data = data else {
            return
        }

        pkClosure?(data)
    }
    
    @discardableResult
    func pkClick(_ closure: @escaping ((RankListModel) -> Void)) -> PkView {
        pkClosure = closure
        return self
    }
}

private class NorView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let img = UIImageView(image: UIImage(named: "rank_add_photo_img"))
        img.frame = CGRect(x: kScreenWidth - 200, y: 50, width: 150, height: 150)
        img.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(addPhotoAction))
        img.addGestureRecognizer(tap)
        addSubview(img)
        
        addsubViews([onlinePkBtn, descImage, descLabel])
        onlinePkBtn.frame = CGRect(x: 30, y: 40, width: 90, height: 35)
        descImage.frame = CGRect(x: 25, y: 70, width: 100, height: 130)
        descLabel.frame = CGRect(x: 0, y: frame.size.height - 90, width: kScreenWidth, height: 20)

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var addPhotoClosure: (() -> Void)?
    private var onlineClosure:(() -> Void)?
    
    private lazy var descImage: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "face_result_double")
        return view
    }()
    
    private lazy var descLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        view.text = "上传自己照片，下一个榜首就是你"
        view.textAlignment = .center
        return view
    }()
    
    
    private lazy var onlinePkBtn: UIButton = {
        let view = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.initWithRGB(215, 100, 72).cgColor
        view.titleLabel?.font = .systemFont(ofSize: 16)
        view.setTitleColor(.initWithRGB(215, 100, 72), for: .normal)
        view.setTitle("实时PK", for: .normal)
        view.addTarget(self, action: #selector(onlineBtnClickAction), for: .touchUpInside)
        return view
    }()
    
    @discardableResult
    func addPhotoClick(_ closure: @escaping (() -> Void)) -> NorView {
        addPhotoClosure = closure
        return self
    }
    
    @discardableResult
    func onlineClick(_ closure: @escaping (() -> Void)) -> NorView {
        onlineClosure = closure
        return self
    }
    
    @objc private func addPhotoAction() {
        addPhotoClosure?()
    }
    
    @objc private func onlineBtnClickAction() {
        onlineClosure?()
    }
}

class RankBottomSliderView: UIView {

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: kScreenHeight - ktabBarHeight, width: kScreenWidth, height: viewHeight + 20))
        backgroundColor = .white
        layer.masksToBounds = true
        layer.cornerRadius = 20
        
        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panAction(_:)))
        addGestureRecognizer(pan)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let viewHeight: CGFloat = 280 + kSafeAreaBottomH
    
    private var onLineClosure: (() -> Void)?
    private var addClosure: (() -> Void)?
    private var pkClosure: ((RankListModel) -> Void)?
    private lazy var minFrameY = kScreenHeight - viewHeight
    private lazy var maxFrameY = kScreenHeight - ktabBarHeight
    private var state = State.addPhtot {
        didSet {
            addPhotoView.isHidden = (state == .pk)
            pkView.isHidden = (state != .pk)
        }
    }
    
    private var isShowUp = true {
        didSet {
            upIcon.image = isShowUp ? UIImage(named: "rank_bottom_up_icon") : UIImage(named: "rank_bottom_down_icon")
        }
    }
    
    private lazy var upIcon: UIImageView = {
        let view = UIImageView(image: UIImage(named: "rank_bottom_up_icon"))
        let tap = UITapGestureRecognizer(target: self, action: #selector(upIconAction))
        view.addGestureRecognizer(tap)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var addPhotoView: NorView = {
        let view = NorView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: viewHeight))
        view.addPhotoClick { [weak self] in
            self?.addClosure?()
        }.onlineClick { [weak self] in
            self?.onLineClosure?()
        }
        return view
    }()
    
    private lazy var pkView: PkView = {
        let view = PkView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: viewHeight))
        view.pkClick { [weak self] model in
            self?.pkClosure?(model)
        }
        view.isHidden = true
        return view
    }()
    
}

extension RankBottomSliderView {
    
    private func setupUI() {
        addsubViews([addPhotoView, pkView, upIcon])
        addPhotoView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: viewHeight)
        upIcon.frame = CGRect(x: kScreenWidth/2 - 12, y: 8, width: 24, height: 24)
    }
    
    @objc private func panAction(_ sender: UIPanGestureRecognizer) {
        let offsetY = sender.translation(in: sender.view).y
        var newFrameY = offsetY + self.frame.origin.y
        if newFrameY <= minFrameY {
            newFrameY = minFrameY
        } else if newFrameY > maxFrameY {
            newFrameY = maxFrameY
        }
        self.frame = CGRect(x: 0, y: newFrameY, width: kScreenWidth, height: viewHeight + 20)
        self.isShowUp = newFrameY >= (maxFrameY + minFrameY)/2
        sender.setTranslation(CGPoint(x: 0, y: 0), in: sender.view)
    }
    
    @objc private func upIconAction() {
        _ = isShowUp ? show() : hide()
    }
}


extension RankBottomSliderView {
    
    @discardableResult
    func setPkModel(model: RankListModel) -> RankBottomSliderView {
        state = .pk
        pkView.data = model
        return self
    }
    
    @discardableResult
    func show() -> RankBottomSliderView {
        isShowUp = false
        UIView.animate(withDuration: 0.25) {
            self.frame = CGRect(x: 0, y: self.minFrameY, width: kScreenWidth, height: self.viewHeight + 20)
        }
        return self
    }
    
    @discardableResult
    func hide() -> RankBottomSliderView {
        isShowUp = true
        UIView.animate(withDuration: 0.25) {
            self.frame = CGRect(x: 0, y: self.maxFrameY, width: kScreenWidth, height: self.viewHeight + 20)
        } completion: { _ in
            self.state = .addPhtot
        }
        return self
    }
    
    @discardableResult
    func pkClick(_ closure: ((RankListModel) -> Void)?) -> RankBottomSliderView {
        pkClosure = closure
        return self
    }
    
    @discardableResult
    func addClick(_ closure: (() -> Void)?) -> RankBottomSliderView {
        addClosure = closure
        return self
    }
    
    @discardableResult
    func onLinePkClick(_ closure: (() -> Void)?) -> RankBottomSliderView {
        onLineClosure = closure
        return self
    }
}
